
package com.kld.test;

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.kld.iodevice.GeneralRespModel;
import com.kld.iodevice.IodeviceWlock;
import com.kld.iodevice.JiuJingModel;
import com.kld.iodevice.PowerModel;
import com.kld.iodevice.WindModel;

import java.io.IOException;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.IllegalFormatCodePointException;
import java.util.List;

import ZtlApi.ZtlManager;
import android_serialport_api.SerialPort;
import tp.xmaihh.serialport.SerialHelper;
import tp.xmaihh.serialport.bean.ComBean;

/**
 * @auther ocean
 * @date 2023-06-15
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    //锁板
    EditText et_locked_plate;
    EditText et_locked_position;
    TextView tvHeadTitle;
    ListView list_view;
    ArrayAdapter<String> myArrayAdapter;
    private static List<String> strs = new ArrayList<>();
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss:SSS");
    private int iRet = -1;
    private int iRet2 = -1;
    private int current = 0;
    private int totalCount = -1;
    private int baseLength = 1024;
    private static final String ACTION_USB_PERMISSION = "com.example.USB_PERMISSION";
//    private PendingIntent permissionIntent;
//    private UsbManager usbManager;
    private SerialHelper serialHelper;
    private Button btn_locked_plate_open;
    private Button btn_locked_plate_read_state;
    private Button btn_locked_plate_read_all;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvHeadTitle = findViewById(R.id.tvHeadTitle);
        findViewById(R.id.tvHeadTitle).setOnClickListener(this);
        findViewById(R.id.id_btninit).setOnClickListener(this);
        findViewById(R.id.id_btndeinit).setOnClickListener(this);
        findViewById(R.id.id_btnclearlog).setOnClickListener(this);
        findViewById(R.id.id_macAddress).setOnClickListener(this);
        //锁板
        et_locked_plate = findViewById(R.id.et_locked_plate);
        et_locked_position = findViewById(R.id.et_locked_position);
        btn_locked_plate_open = findViewById(R.id.btn_locked_plate_open);
        btn_locked_plate_open.setOnClickListener(this);
        btn_locked_plate_read_state = findViewById(R.id.btn_locked_plate_read_state);
        btn_locked_plate_read_state.setOnClickListener(this);
        btn_locked_plate_read_all = findViewById(R.id.btn_locked_plate_read_all);
        btn_locked_plate_read_all.setOnClickListener(this);
        //电源盒

        findViewById(R.id.btn_jiujing_read_state).setOnClickListener(this);
        findViewById(R.id.btn_wind_read_state).setOnClickListener(this);
        findViewById(R.id.btn_power_state_read_state_hum).setOnClickListener(this);

        //二维码
        findViewById(R.id.btn_open).setOnClickListener(this);
        initVersion();
        list_view = findViewById(R.id.list_view);
        myArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, strs);
        list_view.setAdapter(myArrayAdapter);
        //二维码开始识别
        OpenQrSerialPort2();

    }

    private void initVersion() {

        try {
            PackageManager manager = this.getPackageManager();
            PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);

            tvHeadTitle.setText("终端测试程序  V" + info.versionName);
        } catch (Exception e) {
            Log.e("", "获取版本号失败", e);
        }

    }


    private void cleanLog() {
        strs.clear();
        myArrayAdapter.notifyDataSetChanged();
    }

    private void addLog(String value) {
        System.out.print(value.length()+"");
        Log.e("test",value);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                strs.add(sdf.format(new Date()) + " : " + value);
                myArrayAdapter.notifyDataSetChanged();
                list_view.setSelection(list_view.getBottom());
            }
        });

    }

    @Override
    public void onClick(View arg0) {

        switch (arg0.getId()) {
            case R.id.id_btnclearlog:
                cleanLog();
                break;
            case R.id.id_btninit:
//                iRet = IodeviceWlock.devInit("/dev/ttyS3", 115200);

                init();
                break;
            case R.id.id_macAddress: ;
                String macAddress = ZtlManager.GetInstance().getMacAddress();
                addLog("mac地址："+macAddress);
                break;
            case R.id.id_btndeinit:
                unResigster();
                break;

            case R.id.btn_locked_plate_open:
                if (iRet != 0) {
                    Toast.makeText(MainActivity.this, "请先初始化", Toast.LENGTH_LONG).show();
                    return;
                }
                btn_locked_plate_open.setEnabled(false);
                GeneralRespModel respModel = IodeviceWlock.lockedPlateOpen(getLockedPlateNo(), getLockedBoxNo());
                btn_locked_plate_open.setEnabled(true);
                addLog(getLockedPlateNo()+"号锁板" + getLockedBoxNo()+"号锁位，开锁通信"+ (respModel.getCode() == 0 ? "成功" : "失败"));
                break;

            case R.id.btn_locked_plate_read_state:
                if (iRet != 0) {
                    Toast.makeText(MainActivity.this, "请先初始化", Toast.LENGTH_LONG).show();
                    return;
                }
                btn_locked_plate_read_state.setEnabled(false);
                GeneralRespModel respModel2 = IodeviceWlock.lockedPlateRead(getLockedPlateNo(), getLockedBoxNo());
                btn_locked_plate_read_state.setEnabled(true);
                System.out.println("respModel2:" + respModel2.toString());
                if (respModel2.getCode() == 0) {
                    int state = (int) respModel2.getData();
                    if (state == 1) {
                        addLog(getLockedPlateNo()+"号锁板" + getLockedBoxNo()+"锁位状态：开启");
                    } else if (state == 2) {
                        addLog(getLockedPlateNo()+"号锁板" + getLockedBoxNo()+"锁位状态：关闭");
                    } else if (state == 3) {
                        addLog(getLockedPlateNo()+"号锁板" + getLockedBoxNo()+"锁位状态：开启中");
                    } else if (state == 4) {
                        addLog(getLockedPlateNo()+"号锁板" + getLockedBoxNo()+"锁位状态：关闭中");
                    } else if (state == 5) {
                        addLog(getLockedPlateNo()+"号锁板" + getLockedBoxNo()+"锁位状态：异常打开");
                    } else if (state == 6) {
                        addLog(getLockedPlateNo()+"号锁板" + getLockedBoxNo()+"锁位状态：异常关闭");
                    }
                } else {
                    addLog(getLockedPlateNo()+"号锁板" + getLockedBoxNo()+"号锁位读取状态通信"+"：失败");
                }


                break;
            case R.id.btn_locked_plate_read_all:
                if (iRet != 0) {
                    Toast.makeText(MainActivity.this, "请先初始化", Toast.LENGTH_LONG).show();
                    return;
                }
                btn_locked_plate_read_all.setEnabled(false);
                GeneralRespModel respModel3 = IodeviceWlock.lockedPlateReadAll(getLockedPlateNo());
                btn_locked_plate_read_all.setEnabled(true);
                StringBuffer sb = new StringBuffer(getLockedPlateNo()+"号锁板全部读取:");
                if (respModel3.getCode() != 0) {
                    //失败
                    sb.append("通信失败");
                } else {
                    //成功
                    sb.append("通信成功，状态：");

                    List<Integer> dataList = (List<Integer>) respModel3.getData();

                    if (dataList != null && dataList.size() > 0) {
                        for (int i = 0; i < dataList.size(); i++) {
                            sb.append("锁位-" + (i + 1) + "-");
                            if (dataList.get(i) == 2) {
                                sb.append("关闭");
                            } else if (dataList.get(i) == 1) {
                                sb.append("开启");
                            } else if (dataList.get(i) == 3) {
                                sb.append("开启中");
                            } else if (dataList.get(i) == 4) {
                                sb.append("关闭中");
                            } else if (dataList.get(i) == 5) {
                                sb.append("异常打开");
                            } else if (dataList.get(i) == 6) {
                                sb.append("异常关闭");
                            }
                            sb.append("；");
                        }
                    }
                }
                addLog(sb.toString());
                break;


            case R.id.btn_jiujing_read_state:
                if (iRet2 != 0) {
                    Toast.makeText(MainActivity.this, "请先初始化", Toast.LENGTH_LONG).show();
                    return;
                }

                GeneralRespModel jiujing = IodeviceWlock.readJiujing();
                Object data1 = jiujing.getData();

                StringBuffer readjiujing = new StringBuffer("酒精:");
                if (jiujing.getCode() != 0) {
                    //失败
                    readjiujing.append("通信失败");
                } else {
                    //成功
                    readjiujing.append("通信成功\n");
                    if (data1 instanceof JiuJingModel){

                        readjiujing.append("酒精："+((JiuJingModel) data1).getJiujing()+" mg/100ml");
                    }

                }
                addLog(readjiujing.toString());
                break;
            case R.id.btn_wind_read_state:
                if (iRet2 != 0) {
                    Toast.makeText(MainActivity.this, "请先初始化", Toast.LENGTH_LONG).show();
                    return;
                }
                GeneralRespModel wind = IodeviceWlock.readWind();
                StringBuffer readWind = new StringBuffer("风速:");
                Object data2 = wind.getData();
                if (wind.getCode() != 0) {
                    //失败
                    readWind.append("通信失败");
                } else {

                    if (data2 instanceof WindModel){
                        WindModel data21 = (WindModel) data2;
                        int res = data21.getRes();
                        if (res==0){
                            //成功
                            readWind.append("成功");
                            readWind.append("风速状态："+ "吹气正常" +"  res= " +res+";\n");
                            readWind.append("当前吹气最大值： "+ data21.getMaxspeed()+";\n");
                            for (int i = 0; i<data21.getSpeed().length; i++){
                                readWind.append("吹气缓冲值"+(i+1)+":"+ data21.getSpeed()[i]+";\n");
                            }
                        }else  if(res==1){
                            readWind.append("失败 \n");
                            readWind.append("风速状态："+ "吹气力度太小"+"  res=" +res +";\n");
                        }else  if(res==2){
                            readWind.append("失败\n ");
                            readWind.append("风速状态： "+ "未吹气"+"   res=" +res +";\n");
                        }else{
                            readWind.append("风速状态： "+ res +";\n");
                        }



                    }

                }
                addLog(readWind.toString());

                break;
            case R.id.btn_power_state_read_state_hum:
                if (iRet != 0) {
                    Toast.makeText(MainActivity.this, "请先初始化", Toast.LENGTH_LONG).show();
                    return;
                }
                GeneralRespModel readPowerParame = IodeviceWlock.readPowerParame();
                StringBuffer readPower = new StringBuffer("电源参数:");
                if (readPowerParame.getCode() != 0) {
                    //失败
                    readPower.append("通信失败");
                } else {
                    //成功
                    readPower.append("成功，状态：\n");
                    Object data = readPowerParame.getData();
                    if (data instanceof PowerModel){
                        PowerModel powerModel = (PowerModel) data;
                        readPower.append("温度："+powerModel.getWendu()+"℃;\n");
                        readPower.append("湿度："+powerModel.getShidu()+"%RH;\n");
                        if (powerModel.getCharge_state() == 0 ){
                            readPower.append("充电状态：" + "无外接电源" + ";\n");
                        }else  if (powerModel.getCharge_state() == 1 ){
                            if (powerModel.getBat_persent()>95){
                                readPower.append("充电状态：" + "有外接电源,充满" + ";\n");
                            }else{
                                readPower.append("充电状态：" + "有外接电源充电中" + ";\n");
                            }
                        }else  if (powerModel.getCharge_state() == 2 ){
                            readPower.append("充电状态：" + "有外接电源,充满" + ";\n");
                        }

                        readPower.append("电压："+powerModel.getVoltage_mv()*1.0/1000+"v;\n");
                        readPower.append("电量："+powerModel.getBat_persent()+"%;\n");
                    }

                }
                addLog(readPower.toString());
                break;
            case R.id.btn_open:
                OpenQrSerialPort2();
                break;
            case R.id.tvHeadTitle:
                finish();
                break;


            default:
                break;
        }

    }

    //初始化串口4和串口3
    private void init() {
        et_locked_plate.setText("1");
        et_locked_position.setText("1");
        //初始化串口4 电源
        iRet = IodeviceWlock.devInit("/dev/ttyS4", 115200);
        iRet2 = IodeviceWlock.devAdcInit("/dev/ttyS3", 115200);
        StringBuffer sb2 = new StringBuffer("初始化串口:\n");
        if (iRet == 0) {
            sb2.append("串口4初始化成功 \n");
        } else {
            sb2.append("串口4初始化失败：" + iRet+"\n");
        }
        //初始化串口3  酒精，风速

        if (iRet2 == 0) {
            sb2.append("串口3初始化成功 ");
        } else {
            sb2.append("串口3初始化失败：" + iRet2+"");
        }
        addLog(sb2.toString());
    }
    //二维码缓存器
    List<String> cash=new ArrayList<>();

    //开始二维码识别
    private void OpenQrSerialPort2() {

        if (serialHelper==null){
            //串口1  波特率9600
            serialHelper = new SerialHelper("dev/ttyS1", 9600) {
                @Override
                protected void onDataReceived(ComBean comBean) {
                    if (comBean!=null){

                        String str = new String(comBean.bRec,  Charset.forName("GBK"));
                        if (!TextUtils.isEmpty(str)){
                            cash.add(str);
                            //二维码结束符\r\n
                            if (str.endsWith("\r\n")){
                                StringBuffer sb = new StringBuffer();
                                for (String content:cash){
                                    sb.append(content);
                                }
                                addLog("二维码识别成功："+sb.toString());
                                cash.clear();
                            }

                        }


                    }else{

                    }

                }
            };
            try {

                serialHelper.open();
            } catch (IOException e) {
                addLog("二维码识别通信失败");
                throw new RuntimeException(e);
            }

        }

    }

    //注销串口
    private void unResigster() {
        //注销串口4
        StringBuffer sb2 = new StringBuffer("注销串口:\n");
        if (iRet != 0) {
            Toast.makeText(MainActivity.this, "请先初始化", Toast.LENGTH_LONG).show();
            return;
        }
        IodeviceWlock.devDeinit();
        iRet = -1;
        sb2.append("串口4注销成功 \n");


        //注销串口3
        if (iRet2 != 0) {
//                    Toast.makeText(MainActivity.this, "请先初始化", Toast.LENGTH_LONG).show();
            return;
        }
        sb2.append("串口3注销成功 \n");
        IodeviceWlock.devAdcDeinit();
        iRet2 = -1;
        addLog(sb2.toString());
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        IodeviceWlock.devDeinit();
        //页面关闭，关闭二维码串口
        if (serialHelper!=null){
            serialHelper.close();
        }
        //页面关闭关闭串口4，串口3
        unResigster();
    }


    private int getLockedPlateNo() {
        int result = 1;
        String layerStr = et_locked_plate.getText().toString();
        try {
            result = Integer.parseInt(layerStr);
        } catch (Exception e) {
            Toast.makeText(MainActivity.this, "请输入数字", Toast.LENGTH_LONG).show();
            et_locked_plate.setText("1");
        }
        return result;
    }

    private int getLockedBoxNo() {
        int result = 1;
        String layerStr = et_locked_position.getText().toString();
        try {
            result = Integer.parseInt(layerStr);
        } catch (Exception e) {
            Toast.makeText(MainActivity.this, "请输入数字", Toast.LENGTH_LONG).show();
            et_locked_position.setText("1");
        }
        return result;
    }






}